# 创建一个浏览器对象
import datetime
import os.path
import sys
from random import random

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# from webdriver_manager.chrome import ChromeDriverManager
from webdrivermanager_cn.chrome import ChromeDriverManager


class Driver:
    driver = ""
    TestLogs = ""

    def __init__(self):
        # 下载chromedriver，并返回本地路径 创建好的驱动来打开
        driver_path = ChromeDriverManager().install()
        options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(service=Service(driver_path), options=options)
        '''
        service 通过什么样的服务打开浏览器
        options 表示浏览器要添加哪些配置
        '''
        # 添加隐式等待
        self.driver.implicitly_wait(2)

    # 抓取屏幕截图
    def ScreenShot(self):
        # 图片名称: ./2024-08-30-1053.png
        dirName = datetime.datetime.now().strftime('%Y-%m-%d')
        # 判断dirName文件夹是否已经存在，若不存在则创建文件夹
        # ../images/2024-05-08
        if not os.path.exists("../images/" + dirName):
            os.mkdir("../images/" + dirName)
        # 加上调用方法
        filename = (sys._getframe().f_back.f_code.co_name+"-"+datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S") +
                    ".png")
        self.driver.save_screenshot("../images/"+dirName+"/"+filename)

    def log(self, args=""):
        self.TestLogs = (sys._getframe().f_back.f_code.co_name + "-" + datetime.datetime.now().strftime(
            "%Y-%m-%d-%H%M%S") + " " + args + "\n")
        with open('../TestLog/log.txt', 'a+', encoding='utf8') as f:
            # print(f.write(self.TestLogs))
            print(self.TestLogs)


# 其他类想调用 Driver 成员，通过 .BlogDriver 单例
BlogDriver = Driver()
